//
//  MusicViewController.m
//  享动
//
//  Created by lanou on 16/4/7.
//  Copyright © 2016年 HHUI. All rights reserved.

#import "MusicViewController.h"
#import "musicrunCell.h"
#import "RequestManager.h"
#import "MusicDetailViewController.h"
#import "musicRunModel.h"
#import <UIImageView+WebCache.h>
#import "HYAwesomeTransition.h"
#import <FMDatabase.h>
#import "musicListModel.h"
@interface MusicViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate,UIAlertViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>


@property(nonatomic,strong)NSArray * musicUrlArray;


@property(nonatomic,strong)HYAwesomeTransition *  awesometransition;

@property (weak, nonatomic) IBOutlet UIScrollView *scrolllView;

@property (weak, nonatomic) IBOutlet UICollectionView *conllectionView;

@property (weak, nonatomic) IBOutlet UIButton *musiclistButton;

@property (weak, nonatomic) IBOutlet UIButton *mymusicButton;

@property(nonatomic,strong)NSMutableArray * tempArray;

@property(nonatomic,strong)NSMutableArray * modelArray;

@property(nonatomic,strong)NSMutableArray *titleArray;

@property(nonatomic,strong)UIView * addView;

@property(nonatomic,strong) UITextField *  nameT;

@property(nonatomic,strong) UITextField *  nameT1;

@property(nonatomic,strong) UIImageView * iconView;

@property(nonatomic,strong)FMDatabase * db;

@property(nonatomic,strong)NSMutableArray * musicListArray;

@end

@implementation MusicViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _musicListArray = [NSMutableArray array];
    
    // 数据库
    NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"musicList.db"];
    
    self.db = [FMDatabase databaseWithPath:path];
    
    if (![self.db open]) {
        NSLog(@"不能打开数据库");
    }
    
    // 创建表
     [_db executeUpdate:@"CREATE TABLE musicList (listName text,iconViewData blot ,introduce text)"];
    
    FMResultSet * rs = [_db executeQuery:@"SELECT * FROM musicList"];
    
    while ([rs next]) {
        musicListModel * model = [[musicListModel alloc]init];
        model.listName = [rs stringForColumn:@"listName"];
        model.iconViewData = [rs dataForColumn:@"iconViewData"];
        model.introduce = [rs dataForColumn:@"introduce"];
        [_musicListArray addObject:model];
    }
    
    [rs close];
    
    
    
    
    _musicUrlArray = @[@"http://appt.igeekery.com//mix/scene-page.json?_ch=appStore&_k=93b67e0dfaac41078bc7666729f8e993&_lan=ch&_nw=WiFi&_product=fitmix&_sdk=iPhone%20OS8.2&_v=3&index=0&scene=3&uid=301026",@"http://appt.igeekery.com//mix/scene-page.json?_ch=appStore&_k=f98cebca56614844b86bfccd6a725f17&_lan=ch&_nw=WiFi&_product=fitmix&_sdk=iPhone%20OS8.2&_v=3&index=0&scene=2&uid=301026",@"http://appt.igeekery.com//mix/scene-page.json?_ch=appStore&_k=b9d632d4710a49b6830ea250bddff31d&_lan=ch&_nw=WiFi&_product=fitmix&_sdk=iPhone%20OS8.2&_v=3&index=0&scene=1&uid=301026",@"http://appt.igeekery.com//mix/scene-page.json?_ch=appStore&_k=23afcd25481f4710bb760935bf818599&_lan=ch&_nw=WiFi&_product=fitmix&_sdk=iPhone%20OS8.2&_v=3&index=0&scene=4&uid=301026",@"http://appt.igeekery.com//mix/scene-page.json?_ch=appStore&_k=df6f697add4c44f6aa0d328b7726d93d&_lan=ch&_nw=WiFi&_product=fitmix&_sdk=iPhone%20OS8.2&_v=3&index=0&scene=5&uid=301026",@"http://appt.igeekery.com//mix/scene-page.json?_ch=appStore&_k=a87cc5e228db4a82bdfffedbcd600b86&_lan=ch&_nw=WiFi&_product=fitmix&_sdk=iPhone%20OS8.2&_v=3&index=0&scene=6&uid=301026",@"http://appt.igeekery.com//mix/scene-page.json?_ch=appStore&_k=d37e9a14a5c5432da2fd4f3806b2c9a7&_lan=ch&_nw=WiFi&_product=fitmix&_sdk=iPhone%20OS8.2&_v=3&index=0&scene=7&uid=301026"];
    
    self.scrolllView.delegate = self;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = @"享听";
    
    
    [self.musiclistButton addTarget:self action:@selector(musiclist) forControlEvents:UIControlEventTouchUpInside];
    self.musiclistButton.backgroundColor =[UIColor colorWithRed:136/255.0 green:205/255.0 blue:85/255.0 alpha:1];
    [self.mymusicButton addTarget:self action:@selector(mymusic) forControlEvents:UIControlEventTouchUpInside];
    [self.musiclistButton.layer setCornerRadius:5];
    [self.mymusicButton.layer setCornerRadius:5];
    
    
    self.conllectionView.delegate = self;
    self.conllectionView.dataSource = self;
    self.conllectionView.backgroundColor = [UIColor whiteColor];
    [self.conllectionView registerClass:[musicrunCell class] forCellWithReuseIdentifier:@"cell"];
    
    NSArray * imageArr = @[@"http://f.igeekery.com/1001/d2375d96a619485ea744a51c082a5e4a.jpg",@"http://f.igeekery.com/1001/e12ee3b865a1475da0106b9e06a3babb.jpg",@"http://f.igeekery.com/1001/917e3b493f8541d6b8febe1a837c683c.jpg",@"http://f.igeekery.com/1001/b4f90c2a6d784bbcad5a910a1777cf50.jpg",
        @"http://f.igeekery.com/1001/d499c353cc024f62a82fb9b343e0b973.jpg",@"http://f.igeekery.com/1001/fc5b6021005f415e8d09f379668a4f73.jpg",@"http://f.igeekery.com/1001/6d9db5b51656490c9bc7963dade9ebd2.jpg"];
    _modelArray = [NSMutableArray arrayWithArray:imageArr];
    

    NSArray * titile = @[@"慢跑",@"中跑",@"快跑",@"健走",@"热身",@"放松",@"街舞音乐"];
    _titleArray = [NSMutableArray arrayWithArray:titile];
    
    // ADDview
    [self getAddView];
    
}



- (void)viewWillDisappear:(BOOL)animated
{
    _addView.frame =  CGRectMake((KWIDTH-10)/2, KHEIGHT - 10, 10 , 10);
    
}

- (void)getAddView
{
    // 添加歌单
    _addView = [[UIView alloc]initWithFrame:CGRectMake((KWIDTH-10)/2, KHEIGHT - 10, 10 , 10)];
    _addView.backgroundColor = [UIColor darkGrayColor];
    
    [self.view addSubview:_addView];
    
    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 70, 20)];
    label.text = @"歌单名称";
    label.textColor = [UIColor whiteColor];
    [_addView addSubview:label];
    
    _nameT = [[UITextField alloc]initWithFrame:CGRectMake(10, 35, (KWIDTH - 40)/3, 30)];
    _nameT.borderStyle = UITextBorderStyleRoundedRect;
    _nameT.placeholder = @"新建歌单";
    _nameT.clearButtonMode = YES;
    [_addView addSubview:_nameT];
    
    UILabel * label1 = [[UILabel alloc]initWithFrame:CGRectMake(10, 85, 80, 20)];
    label1.text = @"歌单描述";
    label1.textColor = [UIColor whiteColor];
    [_addView addSubview:label1];
    
    _nameT1 = [[UITextField alloc]initWithFrame:CGRectMake(10, 110, (KWIDTH - 40)/3, 30)];
    _nameT1.borderStyle = UITextBorderStyleRoundedRect;
    _nameT1.placeholder = @"简单描述";
    _nameT1.clearButtonMode = YES;
    [_addView addSubview:_nameT1];
    
    _iconView = [[UIImageView alloc]initWithFrame:CGRectMake((KWIDTH-40)/1.5, 10,(KWIDTH-40)/4 , (KWIDTH-40)/3)];
    _iconView.userInteractionEnabled = YES;
    _iconView.backgroundColor = [UIColor whiteColor];
    [_addView addSubview:_iconView];
    
    UIButton * addButton = [UIButton buttonWithType:UIButtonTypeSystem];
    addButton.frame = _iconView.bounds;
    addButton.backgroundColor = [UIColor clearColor];
    [addButton addTarget:self action:@selector(addIconView) forControlEvents:UIControlEventTouchUpInside];
    [_iconView addSubview:addButton];
    
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake((KWIDTH-40)/1.5, 30+(KWIDTH-40)/3 , 40, 20);
    [button setTitle:@"取消" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(quxiao) forControlEvents:UIControlEventTouchUpInside];
    
    [_addView addSubview:button];
    
    
    UIButton * button1 = [UIButton buttonWithType:UIButtonTypeSystem];
    button1.frame = CGRectMake((KWIDTH-40)/1.5 + 50, 30+(KWIDTH-40)/3 , 40, 20);
    [button1 addTarget:self action:@selector(ok) forControlEvents:UIControlEventTouchUpInside];
    [button1 setTitle:@"确定" forState:UIControlStateNormal];
    [button1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_addView addSubview:button1];
  
    
}

- (void)viewWillAppear:(BOOL)animated
{
    
    // 添加键盘弹出的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoard:) name:UIKeyboardWillShowNotification object:nil];
    
    // 添加键盘回收的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(Back:) name:UIKeyboardWillHideNotification object:nil];
    

}

- (void)addIconView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction * a = [UIAlertAction  actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 判断有没有相机
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                
                UIImagePickerController  * picker = [[UIImagePickerController alloc]init];
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                
                // 是否可编辑 默认是no
                picker.allowsEditing = YES;
                [self presentViewController:picker animated:YES completion:nil];
                picker.delegate = self;
            }
            
            else{
                NSLog(@"没有相机");
            }
            
            
            
        }];
        UIAlertAction * b = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                // 类型：类型决定了 展示出来的是什么（相机还是相册） 相册又分两种形式展示
                UIImagePickerController  * picker = [[UIImagePickerController alloc]init];
                
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                
                // 是否可编辑 默认是no
                picker.allowsEditing = YES;
                // 是一个代理方法 picker 需要设置代理  有两个代理协议 最好点进去看
                picker.delegate = self;
                
                
                [self presentViewController:picker animated:YES completion:nil];
            }
            else
            {
                NSLog(@"没有相册");
            }
        }];
        [alert addAction:cancel];
        [alert addAction:a];
        [alert addAction:b];
        
        
        cancel.enabled = YES;
        [self presentViewController:alert animated:YES completion:nil];
        
    });

}
#pragma mark --- 执行拍摄完成之后 或者选择完照片之后 自动调用的代理方法 ---
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSLog(@"%@",info);
    
    self.iconView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    // 返回到自己的界面
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    // _localUrl =(NSURL *)[info valueForKey:UIImagePickerControllerReferenceURL];
    
    
    // NSLog(@"%@",localUrl );
}
// 键盘出现
- (void)keyBoard:(NSNotification *)notication
{
    
    // 拿到键盘弹出后的一个整体的信息
    NSDictionary * info = notication.userInfo;
    
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    // 拿到键盘的size
    CGSize size = [value CGRectValue].size;
    
    
    _addView.frame = CGRectMake(20, KHEIGHT/2 - size.height / 2, KWIDTH-40, KWIDTH/2);
}

// 添加键盘回收的通知
- (void)Back:(NSNotification *)notifica
{
    _addView.frame = CGRectMake(20, KHEIGHT/2, KWIDTH-40, KWIDTH/2);
    
}
// 取消
- (void)quxiao
{
    [UIView transitionWithView:_addView duration:1 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
        _addView.frame =  CGRectMake((KWIDTH-10)/2, KHEIGHT - 10, 10 , 10);
    } completion:nil];
}

// 确定
- (void)ok
{
    
    if (self.iconView.image == nil) {
        self.iconView.image = [UIImage imageNamed:@"7"];
    }
    if (_nameT.text == nil) {
        _nameT.text = @"新建";
    }
    musicListModel * model = [[musicListModel alloc]init];
    model.iconViewData = UIImagePNGRepresentation(_iconView.image);
    model.listName = _nameT.text;
    model.introduce = _nameT1.text;
    
    [_db executeUpdate:@"INSERT INTO musicList (listName,iconViewData,introduce) VALUES (?,?,?)",model.listName,model.iconViewData,model.introduce];
    
    
  
    [UIView transitionWithView:_addView duration:1 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
        _addView.frame =  CGRectMake((KWIDTH-10)/2, KHEIGHT - 10, 10 , 10);
    } completion:nil];
    [self add];
    [self.conllectionView reloadData];
}

// 键盘回收
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_nameT resignFirstResponder];
    [_nameT1 resignFirstResponder];
}

#pragma mark --- 返回每个分区的行数 ---
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _modelArray.count + 1 + _musicListArray.count ;
}


#pragma mark --- 返回cell ---
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    musicrunCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    NSInteger a = _modelArray.count + _musicListArray.count;
    
    if (indexPath.row < 7) {
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:_modelArray[indexPath.row]]];
        
    cell.titlelabel.text = _titleArray[indexPath.row];
    cell.titlelabel.textColor = [UIColor whiteColor];
    }
//    
//    else if (indexPath.row < a)
//    {
//        musicListModel * model = _musicListArray[]
//    }
    else
    {
        cell.titlelabel.text = @"创建歌单";
        cell.titlelabel.textColor = [UIColor whiteColor];
        cell.picImageView.image = [UIImage imageNamed:@"6"];
        cell.picImageView.backgroundColor =[UIColor colorWithRed:136/255.0 green:205/255.0 blue:85/255.0 alpha:1];
    }
    
    
    cell.backgroundColor = [UIColor colorWithRed:136/255.0 green:205/255.0 blue:85/255.0 alpha:1];
    
    // cell 的边框
    cell.layer.borderColor = [UIColor grayColor].CGColor;
    cell.layer.borderWidth = 0.5;
    
    return cell;
}
// 点击cell 的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < 7) {
       
        NSString * url = _musicUrlArray[indexPath.row];
        
           MusicDetailViewController * musicDetail = [[MusicDetailViewController alloc]initWithNibName:@"musicDetail" bundle:[NSBundle mainBundle]];
        
        
        musicDetail.urlString = url;
        musicDetail.typeString = _titleArray[indexPath.row];
        [self.navigationController pushViewController:musicDetail animated:YES];
        
        
    }
    else if (indexPath.row<_modelArray.count && indexPath.row >=7)
    {
          MusicDetailViewController * musicDetail = [[MusicDetailViewController alloc]initWithNibName:@"musicDetail" bundle:[NSBundle mainBundle]];
         [self.navigationController pushViewController:musicDetail animated:YES];
    }
    
    if (indexPath.row == _modelArray.count) {
        self.iconView.image = nil;
        self.nameT.text = nil;
        self.nameT1.text = nil;
  [UIView transitionWithView:_addView duration:1 options:UIViewAnimationOptionTransitionFlipFromTop animations:^{
            _addView.frame = CGRectMake(20, KHEIGHT/2, KWIDTH-40, KWIDTH/2);
        } completion:nil];
}
}

// 添加歌单
- (void)add
{
    [_modelArray insertObject:@"runStart" atIndex:_modelArray.count];
    [_titleArray insertObject:@"新建" atIndex:_titleArray.count];
}



#pragma mark --- 返回每个item宽和高 ---
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat width = (KWIDTH - 40)/3;
    CGFloat height = (KWIDTH - 40)/3 + 35;
    return CGSizeMake(width, height);
}


#pragma mark --- 控制集合视图的行边距 ---
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}


#pragma mark --- 控制集合视图的列边距 ---
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return  UIEdgeInsetsMake(10, 5, 10, 5);
}





- (void)musiclist
{
    self.musiclistButton.backgroundColor =[UIColor colorWithRed:136/255.0 green:205/255.0 blue:85/255.0 alpha:1];
    self.mymusicButton.backgroundColor = [UIColor lightGrayColor];
    [UIView animateWithDuration:0.5 animations:^{
        [self.scrolllView setContentOffset:CGPointMake(0, 0)];
        
    }];
}


- (void)mymusic
{
    self.mymusicButton.backgroundColor =[UIColor colorWithRed:136/255.0 green:205/255.0 blue:85/255.0 alpha:1];
    self.musiclistButton.backgroundColor = [UIColor lightGrayColor];
    [UIView animateWithDuration:0.5 animations:^{
        [self.scrolllView setContentOffset:CGPointMake(KWIDTH, 0)];
    }];
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == _scrolllView) {
        if (scrollView.contentOffset.x / KWIDTH == 0) {
            self.musiclistButton.backgroundColor =[UIColor colorWithRed:136/255.0 green:205/255.0 blue:85/255.0 alpha:1];
            self.mymusicButton.backgroundColor = [UIColor lightGrayColor];
        }
        else
        {
            self.mymusicButton.backgroundColor =[UIColor colorWithRed:136/255.0 green:205/255.0 blue:85/255.0 alpha:1];
            self.musiclistButton.backgroundColor = [UIColor lightGrayColor];
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
